<?php

namespace app\api;

use app\Controller;
use app\util\Mysql;
use app\util\ConstCode;
use app\util\Tfidf;

/**
 * 首页
 */
class Search extends Controller
{
    public $check_user = false;//首页不验证登录
    public $restrictAccess = true;//是否限制访问：true限制访问，false不限制访问

    /**
     * @return void
     */
    public function index(){
        if(empty($_POST["text"])){
            error('请输入搜索内容');
        }
        $text = $_POST["text"];

        $result = $this->tfidf($text);//tfidf搜索
        success('success','',$result);
    }

    /**
     * @param $text
     * @return array
     */
    public function tfidf($text){
        if(empty($_SESSION['username'])){
            error('您先登录！');
        }

        $database = Mysql::init();
        $username = $_SESSION['username'];
        $gid = $database->get("user_text", "gid", ["username" => $username]);

        $where = [
            "AND #0" => [
                "OR #2" => [
                    "creator" => $username,
                    "AND #20" => [
                        "creator[!]" => "",
                        "gid" => $gid,
                        "gread[!]" => ConstCode::READ_NO
                    ], "AND #21" => [
                        "creator[!]" =>
                            $username,
                        "gid[!]" => $gid,
                        "otherread[!]" => ConstCode::READ_NO
                    ]
                ],
                "status" => ConstCode::STATUS_NORMAL
            ]
        ];
        $count = $database->count("text_main",
            ["[>]text_auth" => ["tid"]],
            "tid",
            $where);
        if(empty($count)){
            error('没有找到相关内容');
        }

        //查询数据
        $data = $database->select("text_main",
            ["[>]text_auth" => ["tid"]],
            ["tid", "textname", "creator", "created",'main'],
            $where);

        //数据处理
        foreach ($data as &$value){
            $value['created'] = date('Y-m-d H:i:s',$value['created']);
            $value['text'] = $value['textname'].$value['main'];
        }

        $service = (new Tfidf());
        $service->setDocuments($data);
        $data = $service->search($text);
        if(empty($data)){
            error('没有找到相关内容');
        }
        return[
            "count" => $count,
            "list" => $data
        ];
    }

}
